#!/usr/bin/env bash

# nohup bash JobLauncher.sh sth --infinity --sleep=1m > /dev/null 2>&1 &

ROOT_DIR=$(dirname `readlink -m $0`)
shStatusDir="$ROOT_DIR/cache/data"
shStatusFile="$shStatusDir/$$"

phpCommand="php $ROOT_DIR/tasks/cli.php"
infinity=0
isLoop=0
sleepTime="1m"

for((i=1;i<$#+1;i++));do
    if [ "${!i}" = "--loop" ]; then
        isLoop=1
        continue
    elif [ "${!i}" = "--infinity" ]; then
        infinity=1
        isLoop=1
        continue
    elif [ "${!i:0:8}" = "--sleep=" ]; then
        sleepTime=`echo ${!i} | sed -e 's/--sleep=//'`
        continue
    fi

    phpCommand="${phpCommand} ${!i}"
done

# 删除标志文件
if [ -f ${shStatusFile} ]; then
    rm -f ${shStatusFile}
fi

if [ ${isLoop} -eq 0 ]; then
     ${phpCommand}
else
    touch ${shStatusFile}
    phpCommand="${phpCommand} --flag=${shStatusFile}"
    while [ true ];do
        ${phpCommand}

        EXEC_FLAG=`cat ${shStatusFile}`
        if [ "${EXEC_FLAG}" = 'continue' ]; then
            continue
        fi

        if [ "${EXEC_FLAG}" = 'sleep' -o "${EXEC_FLAG}" = '' ]; then
            sleep ${sleepTime}
            continue
        fi

        if [ ${infinity} -eq 0 -a "${EXEC_FLAG}" = "stop" ]; then
            rm -f ${shStatusFile}
            break
        fi

        sleep ${sleepTime}
    done
fi